package main

import (
	"git.oschina.net/xuebing1110/wechat"
	"github.com/chanxuehong/wechat/mp"
	//"github.com/chanxuehong/wechat/mp/menu"
	"flag"
	"github.com/chanxuehong/wechat/mp/message/request"
	"github.com/chanxuehong/wechat/util"
	"log"
	"net/http"
	"strconv"
)

/*const (
	TOKEN          = "public"
	EncodingAESKey = "eetTsjMy6uG6S4tr3D0u6uYhpn7dP9uwHKn98vAhV32"
	APPID          = "wx2e08b5922e0903d1"
	ORIID          = "gh_b2db216a9347"
	port           = "5600"
	GAODE_KEY      = "b3abf03fa1e83992727f0625a918fe73"
	DBTYPE         = "sqlite3"
	DBFILE         = "/xuebing/wechat/db/talkabout.db"
)*/

func init() {
	wechat.Register(wechat.MATCHTYPE_PREFIX, "姓名@", wechat.RegNameHandler)
	wechat.Register(wechat.MATCHTYPE_PREFIX, "琴岛通@", wechat.QDTBindHandler)
	wechat.Register(wechat.MATCHTYPE_EQUAL, "头像", wechat.RegHeadTextHandler)
	wechat.Register(wechat.MATCHTYPE_PREFIX, "公交卡余额", wechat.TransCardQueryHandler)
}

type DevImage struct {
	PicUrl     string
	UserID     string
	CreateTime string
}

func main() {
	conf_file := flag.String("f", "/etc/wechat.yaml", "configure file")
	flag.Parse()

	//*conf_file = `F:\DIR_GIT\src\git.oschina.net\xuebing1110\wechat\etc\wechat.yaml`
	//log.Println(*conf_file)

	config, c_err := wechat.LoadConfig(*conf_file)
	if c_err != nil {
		log.Panicln(c_err)
	}

	aesKey, err := util.AESKeyDecode(config.EncodingAESKey)
	if err != nil {
		log.Panic(err)
	}

	messageServeMux := mp.NewMessageServeMux()
	messageServeMux.MessageHandleFunc(request.MsgTypeText, wechat.TextMessageHandler)
	messageServeMux.MessageHandleFunc(request.MsgTypeImage, wechat.ImageMessageHandler)
	messageServeMux.MessageHandleFunc(request.MsgTypeLocation, wechat.LocationHandler)
	messageServeMux.EventHandleFunc(request.EventTypeSubscribe, wechat.SubscribeHandler)
	messageServeMux.EventHandleFunc(request.EventTypeUnsubscribe, wechat.UnsubscribeHandler)
	//messageServeMux.EventHandleFunc(menu.EventTypeClick, wechat.MenuHandler)
	//messageServeMux.EventHandleFunc(menu.EventTypeView, wechat.MenuHandler)

	// 下面函数的几个参数设置成你自己的参数: oriId, token, appId
	mpServer := mp.NewDefaultServer(config.OriID,
		config.Token,
		config.AppID,
		aesKey,
		messageServeMux)

	mpServerFrontend := mp.NewServerFrontend(mpServer, mp.ErrorHandlerFunc(wechat.ErrorHandler), nil)

	log.Printf("init %s:%s", config.DBTYPE, config.DBString)
	err = wechat.InitDB(config.DBTYPE, config.DBString)
	if err != nil {
		log.Panic(err)
	}

	// 如果你在微信后台设置的回调地址是
	//   http://xxx.yyy.zzz/wechat
	// 注册 http.Handler
	log.Printf("listen port %v ...", config.Port)
	http.Handle("/wechat", mpServerFrontend)
	err = http.ListenAndServe(":"+strconv.Itoa(config.Port), nil)
	if err != nil {
		log.Panic(err)
	}
}
